package com.qiyuesuo.client.service;

import com.qiyuesuo.client.controller.UploadController;
import com.qiyuesuo.client.util.RSA.RSASignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Scanner;
import java.util.UUID;

/**
 * @author s77
 * @create 2020-4月-03 10:04
 */
@Service("fileService")
public class FileServiceImpl implements FileService {
    private final static Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);


    @Override
    public HttpURLConnection gethttpConn(String REQUEST_PATH, String METHOD) {
        HttpURLConnection httpConn = null;
        try {
            logger.info("连接 -- " + REQUEST_PATH + "-- " + METHOD);
            URL url = new URL(REQUEST_PATH);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setConnectTimeout(300); // 设置发起连接的等待时间，0.3s
            httpConn.setReadTimeout(3000); // 设置数据读取超时的时间，3s
            httpConn.setUseCaches(false); // 设置不使用缓存
            httpConn.setDoOutput(true);
            httpConn.setRequestMethod(METHOD);// GET || POST

            //请求头签名  X-SID和X-Signature
            String xsid = UUID.randomUUID().toString().replaceAll("-", "");
            String xsignature = "";
            String privateKey = "";
            InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("privateKey.txt");
            try (Scanner scanner = new Scanner(is)) {
                while (scanner.hasNextLine()) {
                    privateKey += scanner.nextLine();
                }
            } catch (Exception e) {
                logger.error("读取私钥文件失败", e);
            }
            xsignature = RSASignature.sign(xsid, privateKey);


            httpConn.setRequestProperty("X-SID", xsid);
            httpConn.setRequestProperty("X-Signature", xsignature);
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");

        } catch (ProtocolException e) {
            logger.error("连接到" + REQUEST_PATH + "/" + METHOD + "失败", e);
        } catch (MalformedURLException e) {
            logger.error("连接到" + REQUEST_PATH + "/" + METHOD + "失败", e);
        } catch (IOException e) {
            logger.error("连接到" + REQUEST_PATH + "/" + METHOD + "失败", e);
        }
        return httpConn;

    }

    @Override
    public String info(HttpURLConnection httpConn) {
        // 读取返回数据
        StringBuffer strBuf = new StringBuffer();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream(),"UTF-8"));
            String line = null;
            while ((line = reader.readLine()) != null) {
                strBuf.append(line).append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return strBuf.toString();
    }

}
